const api = require('../../utils/api.js');

const app = getApp();
let timer = null;
Page({
  data: {
    img_url: app.siteInfo.domain + 'addons/ws_micro_shop/core/web/statics/images/',
    contact_tel: '',
    show_customer_service: 0,
    mobile: '',
    unit: '',
    isShow: false,
    phone: '',
    checkcode: '',
    showbindbox: false,
    ismoblie: false,
    issend: false,
    countdown: 120,
    isWXWork: app.isWXWork || false,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    imgUrl: app.imgUrl,
  },
  onLoad(options) {
    let that = this;
    let opts = options || {};
    app.pageOnLoad(this);
    let store = wx.getStorageSync('store');
    let sessionFormStr = {
      shop_id: app.ws_micro_shop_globalData.shopid,
    };
    let serviceMessageTitle = '';
    let serviceMessagePath = 'user';

    let systemInfo = wx.getSystemInfoSync();
    let isiOS = !!(systemInfo.system.toLowerCase().search('ios') + 1);

    this.setData({
      isiOS,
      opts,
      store,
      sessionFormStr: JSON.stringify(sessionFormStr),
      serviceMessagePath,
      serviceMessageTitle,
      template_type: app.ws_micro_shop_globalData.template_type,
    });
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    this.checkCard();
    this.wechatworker();
    this.mobile();
  },
  bindLogin(e) {
    let { url } = e.currentTarget.dataset;
    let { user_info, mobile, isShow, isPhoneNum } = this.data;
    if (Number(user_info.info) === 1 && this.data.mobile != '') {
      app.util.navigateTo(url);
    }
  },
  mobile() {
    let userInfo = wx.getStorageSync('user_info');
    let mobile = (userInfo && userInfo.mobile) || '';
    if (mobile) {
      let strNum = mobile;
      var mobiles = strNum;
      // var mobiles = strNum.substr(0, 3) + '****' + strNum.substr(7);
    }
    this.setData({
      mobile,
      mobiles,
    });
  },
  wechatworker() {
    let that = this;
    app.util.request({
      url: 'common/wechatworker/geCsInfo',
      data: {},
      showLoading: false,
      success: function(res) {
        res.data.data &&
          res.data.data.status &&
          that.setData({
            plugid: res.data.data.plugid,
          });
      },
      fail: function(err) {
        console.log('fail', err);
      },
    });
  },
  hidePop() {
    this.setData({
      openContact: false,
    });
  },
  showPop() {
    this.setData({
      openContact: true,
    });
  },
  startmessage: function(e) {
    // body...
  },
  openCard(e) {
    let { type } = e.currentTarget.dataset;
    let content = Number(type) === 0 ? '免费开通VIP会员，充值购买更优惠！' : '免费开通VIP会员，积分当钱花！';
    wx.showModal({
      title: '温馨提示',
      content,
      success: res => {
        if (res.confirm) {
          this.member();
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      },
    });
  },
  completemessage: function(e) {
    // -3006，当前已是好友，提示退出小程序进行对话。个人不再受到[服务通知]推送
    if (e.detail.errcode === -3006) {
      return wx.showModal({
        title: '提示',
        content:
          '您已添加该客服为您的微信好友，您可以退出小程序并从您的[通讯录]-[企业微信联系人]中找到该客服进行对话。',
      });
    }
    if (e.detail.errcode === -3005) {
      return wx.showToast({
        title: '客服消息发送失败',
        duration: 1500,
        icon: 'none',
      });
    }
    if (e.detail.errcode === -3008) {
      return wx.showToast({
        title: '当前配置没有客服人员',
        duration: 1500,
        icon: 'none',
      });
    }
    if (e.detail.errcode === 0) {
      wx.showToast({
        title: '消息已发送成功，请查看邀请通知',
        duration: 1500,
        icon: 'none',
      });
    }
  },
  loadData() {
    let that = this;
    let pages_user_user = wx.getStorageSync('pages_user_user');
    if (pages_user_user) {
      that.setData(pages_user_user);
    }
    app.ws_micro_shoprequest({
      url: Number(this.data.template_type) === 1 ? api.user.index_new : api.user.index,
      success: function(res) {
        if (res.code === 0) {
          app.wxAppParams(res.data.menus, 'url');
          that.setData(res.data);
          wx.setStorageSync('pages_user_user', res.data);
          wx.setStorageSync('share_setting', res.data.share_setting);
          wx.setStorageSync('user_info', res.data.user_info);
          wx.setStorageSync('member_card_info', res.data.member_card_info);
          wx.setStorageSync(
            'index_member_card_bg',
            res.data.index_member_card_bg
          );
          that.mobile();
        }
      },
    });
  },
  onShow() {
    this.loadData();

    // 多店，来自门店列表页时，只显示订单。
    let fromHome =
      (app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.fromHome) ||
      false;
    let isMulti =
      app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isMulti; // 是否为多店
    this.setData({
      fromHome,
      isMulti,
      isBrand:
        (app.ws_micro_shop_globalData &&
          app.ws_micro_shop_globalData.isBrand) ||
        false,
    });
    fromHome && wx.hideTabBar();
    if (fromHome && isMulti) app.ws_micro_shop_globalData.shopid = 0;
  },
  onHide() {
    timer && clearInterval(timer);
  },
  onUnload() {
    timer && clearInterval(timer);
  },
  callTel(e) {
    let tel = e.currentTarget.dataset.tel;
    if (tel) {
      wx.makePhoneCall({
        phoneNumber: tel,
      });
    } else {
      wx.showToast({
        title: '商家没留手机哦',
        icon: 'none',
      });
    }
  },
  apply(e) {
    let that = this;
    let share_setting = wx.getStorageSync('share_setting');
    let user_info = wx.getStorageSync('user_info');
    let condition = Number(share_setting.share_condition);
    if (user_info.is_distributor != 1) {
      if (condition === 1 || condition === 3) {
        wx.navigateTo({
          url: '/ws_micro_shop_seller/pages/add-share/index',
        });
      } else if (condition === 0 || condition === 2) {
        if (Number(user_info.is_distributor) === 0) {
          wx.showModal({
            title: '申请成为' + this.data.alias,
            content: '是否申请？',
            success: function(r) {
              if (r.confirm) {
                wx.showLoading({
                  title: '正在加载',
                  mask: true,
                });
                app.ws_micro_shoprequest({
                  url: api.share.join,
                  method: 'POST',
                  data: {
                    form_id: e.detail.formId,
                  },
                  success: function(res) {
                    if (res.code === 0) {
                      if (condition === 0) {
                        user_info.is_distributor = 2;
                        wx.navigateTo({
                          url: '/ws_micro_shop_seller/pages/add-share/index',
                        });
                      } else {
                        user_info.is_distributor = 1;
                        app.util.navigateTo(
                          '/ws_micro_shop_seller/pages/share/index',
                          {
                            title: '成为' + that.data.alias,
                          },
                          ''
                        );
                      }
                      wx.setStorageSync('user_info', user_info);
                    }
                  },
                  complete: function() {
                    wx.hideLoading();
                  },
                });
              }
            },
          });
        } else {
          wx.navigateTo({
            url: '/ws_micro_shop_seller/pages/add-share/index',
          });
        }
      }
    } else {
      wx.navigateTo({
        url: '/ws_micro_shop_seller/pages/share/index',
      });
    }
  },
  verify() {
    wx.scanCode({
      onlyFromCamera: false,
      success: function(res) {
        wx.navigateTo({
          url: '/' + res.path,
        });
      },
      fail: function() {
        wx.showToast({
          title: '失败',
        });
      },
    });
  },
  member() {
    wx.navigateTo({
      url: '/ws_micro_shop_seller/pages/vip-center/vip-center',
    });
  },
  getuserinfo(e) {
    let { type } = e.currentTarget.dataset;
    app.ws_micro_shoplogin(1).then(res => {
      if (e.detail.errMsg === 'getUserInfo:ok') {
        let that = this;
        const systemInfo = wx.getSystemInfoSync();
        app.ws_micro_shoprequest({
          url: api.passport.info,
          data: {
            user_info: JSON.stringify(e.detail.userInfo),
            encrypted_data: e.detail.encryptedData,
            iv: e.detail.iv,
            brand: systemInfo.brand,
            model: systemInfo.model,
          },
          method: 'POST',
          success: function(res) {
            if (res.code === 0) {
              type !== 'help' && wx.showToast({ title: '操作成功' });
              that.loadData();
            }
          },
        });
      }
    })
  },
  bindphone(e) {
    let that = this;
    app.ws_micro_shoplogin(1).then(res => {
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        app.ws_micro_shoprequest({
          url: api.passport.bind_mobile,
          data: {
            encrypted_data: e.detail.encryptedData,
            iv: e.detail.iv,
          },
          method: 'POST',
          success: function(res) {
            if (res.code === 0) {
              wx.showToast({
                title: '手机号绑定成功',
                icon: 'success',
              });
              that.setData({
                mobile: res.data.mobile,
              });
              that.loadData();
            } else {
              wx.showModal({
                title: '提示',
                content: '绑定失败，请重新登录',
                success: function(res) {
                  if (res.confirm) {
                    that.bindphone(e);
                  }
                },
              });
            }
          },
        });
      } else {
        wx.showToast({
          title: '您已取消绑定该操作',
          icon: 'none',
        });
      }
    });
  },
  onNavigate(e) {
    let url = e.currentTarget.dataset.url;

    if (this.data.fromHome) {
      if (url.indexOf('?') !== -1) {
        url = url + '&fromHome=1';
      } else {
        url = url + '?fromHome=1';
      }
    }

    app.util.navigateTo(url);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },

  // 检查用户是否有名片
  checkCard() {
    let that = this;
    const openid = wx.getStorageSync('OPENID');
    app.util.request({
      url: 'card/api/have_cared',
      data: { openid },
      success: function(res) {
        if (res.data.errno === 0) {
          that.setData({ haveCard: true });
        } else {
          that.setData({ haveCard: false });
        }
      },
      fail: function(res) {
        that.setData({ haveCard: false });
      },
    });
  },

  // 名片入口
  myCardEntry(e) {
    let { haveCard } = this.data;
    if (haveCard) {
      app.util.navigateTo('/common/component/universal-card/card-preview');
    } else {
      app.util.navigateTo('/common/component/universal-card/pages/card-edit');
    }
  },
  // 会员卡入口
  memberCard() {
    let user_info = wx.getStorageSync('user_info');
    if (user_info.unionid) {
      wx.navigateTo({
        url: '/ws_micro_shop/pages/memberCard/index',
      });
    } else {
      this.setData({
        isShow: true,
      });
    }
  },

  tabMiniCard(e) {
    let args = e.detail;
    let currentPath = '';
    let pages = getCurrentPages();
    pages.length > 0 && (currentPath = '/' + pages.pop().route);
    currentPath !== args.path &&
      setTimeout(() => {
        app.util.navigateTo(args.path, args.query);
      }, 500);
  },

  copyrightLoaded() {
    let that = this;
    app.util.request({
      url: 'auth/session/builtins',
      success: res => {
        let builtins = res.data.data;
        that.setData({ builtins });
      },
    });
  },

  entrySubPackage(e) {
    let url = e.currentTarget.dataset.url;
    app.util.navigateTo(url);
  },

  entryRider(e) {
    if (this.data.user_info.info == 0) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 1500,
        mask: false,
      });
      return false;
    } else {
      let url = e.currentTarget.dataset.url;
      app.util.navigateTo(url);
    }
  },

  showBindBox() {
    this.setData({
      showbindbox: true,
    });
  },

  catchTap() {
    // it`s necessary
  },

  hideBindBox() {
    this.setData({
      showbindbox: false,
    });
  },

  getTelNumber(e) {
    let phone = e.detail.value.trim();
    if (app.util.phoneExp.mobile.test(phone)) {
      this.setData({
        phone,
        ismoblie: true,
      });
    } else {
      this.setData({
        ismoblie: false,
      });
    }
  },

  getCheckCodeValue(e) {
    this.setData({
      checkcode: e.detail.value.trim(),
    });
  },

  getCheckCode() {
    let that = this;
    let { countdown, phone } = that.data;
    app.ws_micro_shoprequest({
      url: api.user.getcheckcode,
      data: {
        phone,
      },
      method: 'POST',
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            issend: true,
          });
          timer = setInterval(function() {
            if (countdown > 1) {
              countdown -= 1;
              that.setData({
                countdown,
              });
            } else {
              timer && clearInterval(timer);
              that.setData({
                countdown: 300,
                issend: false,
              });
            }
          }, 1000);
        }
      },
    });
  },

  bindAddMember() {
    let that = this;
    let { phone, checkcode: code, user_info } = that.data;
    if (!phone) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      });
      return;
    }
    if (!code) {
      wx.showToast({
        title: '请输入正确的验证码',
        icon: 'none',
      });
      return;
    }
    app.ws_micro_shoprequest({
      url: api.user.userbind,
      data: {
        phone,
        code,
      },
      method: 'POST',
      success: function(res) {
        if (res.code === 0) {
          user_info.is_bind = 0;
          wx.showToast({
            title: '绑定成功',
            icon: 'success',
          });
          that.setData({
            user_info,
            showbindbox: false,
          });
        } else {
          wx.showToast({
            title: res.msg || '绑定失败',
            icon: 'none',
          });
        }
      },
    });
  },

  homeNavigation(e) {
    app.ws_micro_shop_globalData.fromHome = true;
    let url =
      e.currentTarget.dataset.type === 'cart'
        ? this.data.isBrand
          ? 'ws_micro_shop/pages/storelist/index'
          : 'ws_micro_shop/pages/cart/cart'
        : 'ws_micro_shop/pages/home/index';
    let params = this.data.isBrand ? { name: '全部', id: 0 } : {};
    app.util.navigateTo(url, params, true);
  },
});
